package com.beau.sqlSession;

import com.beau.config.BoundSql;
import com.beau.pojo.Configuration;
import com.beau.pojo.MappedStatement;
import com.beau.utils.GenericTokenParser;
import com.beau.utils.ParameterMapping;
import com.beau.utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor {


    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        // 获取连接
        Connection conn = configuration.getDataSource().getConnection();
        // 准备 sql 语句
        BoundSql boundSql = getBoundSql(mappedStatement.getSql());
        // 获取 PrepareStatement
        PreparedStatement ps = conn.prepareStatement(boundSql.getSqlText());
        // 填充参数
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        Class<?> parameterClassType = getClassType(mappedStatement.getParameterType());
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();
            Field declaredField = parameterClassType.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);
            ps.setObject(i + 1, o);
        }
        // 执行 Sql
        List<Object> result = new ArrayList<>();
        ResultSet resultSet = ps.executeQuery();
        Class<?> resultClassType = getClassType(mappedStatement.getResultType());
        while (resultSet.next()) {
            Object instance = resultClassType.getDeclaredConstructor().newInstance();
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                String columnName = metaData.getColumnName(i);
                Object value = resultSet.getObject(columnName);
                Method writeMethod = new PropertyDescriptor(columnName, resultClassType).getWriteMethod();
                writeMethod.invoke(instance, value);
            }
            result.add(instance);
        }
        return (List<E>) result;
    }

    @Override
    public int update(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        // 获取连接
        Connection conn = configuration.getDataSource().getConnection();
        // 准备 sql 语句
        BoundSql boundSql = getBoundSql(mappedStatement.getSql());
        // 获取 PrepareStatement
        PreparedStatement ps = conn.prepareStatement(boundSql.getSqlText());
        // 填充参数
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        Class<?> parameterClassType = getClassType(mappedStatement.getParameterType());
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();
            Field declaredField = parameterClassType.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);
            ps.setObject(i + 1, o);
        }
        ps.execute();
        return ps.getUpdateCount();
    }

    private BoundSql getBoundSql(String sql) {
        ParameterMappingTokenHandler tokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser tokenParser = new GenericTokenParser("#{", "}", tokenHandler);
        String sqlText = tokenParser.parse(sql);
        List<ParameterMapping> parameterMappings = tokenHandler.getParameterMappings();
        return new BoundSql(sqlText, parameterMappings);
    }

    private Class<?> getClassType(String parameterType) throws ClassNotFoundException {
        if (parameterType != null) {
            Class<?> aClass = Class.forName(parameterType);
            return aClass;
        }
        return null;
    }
}
